using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;

namespace WeChat.Api.Common
{
    /// <summary>
    /// 系统中常用的一些IO操作：磁盘空间检测、文件创建等
    /// </summary>
    public class FileHelper
    {

        /// ******************************************************************
        #region 模板生成网页专用
        /// ******************************************************************
        /// <summary>
        /// 模板读取文件内容
        /// </summary>
        /// <returns></returns>
        public static string ReadFile(string strFileName)
        {
            string strUrlText = "";
            if (File.Exists(strFileName))
            {
                StreamReader sr = new StreamReader(strFileName, System.Text.Encoding.GetEncoding("gb2312"));
                strUrlText = sr.ReadToEnd();
                sr.Close();
            }
            return strUrlText;
        }
        /// <summary>
        /// 模板自动生成网页文件
        /// </summary>
        /// <param name="sFilePath">文件路径</param>
        /// <param name="sContent">文件内容</param>
        public static void CreatNewFile(string sFilePath, string sContent)
        {
            string dir = sFilePath.Substring(0, sFilePath.LastIndexOf("\\"));
            CreatFolder(dir);
            if (!File.Exists(sFilePath))
            {
                System.IO.FileStream myFileStream = new System.IO.FileStream(sFilePath, System.IO.FileMode.Create);
                myFileStream.Close();
            }
            System.IO.StreamWriter sw = new StreamWriter(sFilePath, false, System.Text.Encoding.GetEncoding("utf-8"));
            sw.Write(sContent);
            sw.Close();
        }
        /// <summary>
        /// 模板自动生成网页文件
        /// </summary>
        /// <param name="sFilePath">文件路径</param>
        /// <param name="sContent">文件内容</param>
        /// <param name="sContent">文件编码</param>
        public static void CreatNewFile(string sFilePath, string sContent, string sEncode)
        {
            string dir = sFilePath.Substring(0, sFilePath.LastIndexOf("\\"));
            CreatFolder(dir);
            if (!File.Exists(sFilePath))
            {
                System.IO.FileStream myFileStream = new System.IO.FileStream(sFilePath, System.IO.FileMode.Create);
                myFileStream.Close();
            }
            System.IO.StreamWriter sw = new StreamWriter(sFilePath, false, System.Text.Encoding.GetEncoding("utf-8"));
            sw.Write(sContent);
            sw.Close();
        }
        public static void CreatFolder(string directoryName)
        {
            if (!Directory.Exists(directoryName))
            {
                Directory.CreateDirectory(directoryName);
            }
        }
        #endregion
        /// ******************************************************************
        /// <summary>
        /// 读取文件内容
        /// </summary>
        /// <returns></returns>
        public static string ReadFile(string strFileName, string encoding)
        {
            string strUrlText = string.Empty;
            if (File.Exists(strFileName))
            {
                StreamReader sr = new StreamReader(strFileName, string.IsNullOrEmpty(encoding) ? System.Text.Encoding.Default : System.Text.Encoding.GetEncoding(encoding));
                strUrlText = sr.ReadToEnd();
                sr.Close();
            }
            return strUrlText;
        }
        public static void AddLog(string LogContent, string FloderName)
        {
            LogContent = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss").ToString() + ":  " + LogContent;
            string strtime = DateTime.Now.ToString("yyyy-MM-dd").ToString();
            string path = "UpFile/PushLog/" + FloderName + "/" + DateTime.Now.ToString("yyyy-MM-dd").ToString() + ".txt";
            CreatePath("UpFile/PushLog/" + FloderName);
            if (!FileExist(path))
            {
                CreatFile(path);
            }
            AddSaveFile(path, LogContent, "utf-8");
        }
        ///******************************************************************
        /// ******************************************************************
        /// <summary>
        /// 向文件添加文本
        /// </summary>
        /// <param name="strFileName">文件路径</param>
        /// <param name="strText">文件内容</param>
        /// <param name="strEncode">存储编码 utf-8  gb2312</param>
        /// <returns></returns>
        public static bool AddSaveFile(string strFileName, string strText, string strEncode)
        {
            if (strText.Length < 1) { return false; }

            StreamWriter urlWrite = new StreamWriter(strFileName, true, Encoding.GetEncoding(strEncode));
            urlWrite.WriteLine(strText);
            urlWrite.Close();

            return true;
        }
      
        /// ******************************************************************
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <returns></returns>
        public static int DeleteFile(string strFileName)
        {
            if (File.Exists(strFileName))
            {
                File.Delete(strFileName);
                return 1;
            }
            else
            {
                return 0;
            }

        }
        /// ******************************************************************
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <returns></returns>
        public static void DelFile(string strFileName)
        {
            if (File.Exists(strFileName))
            {
                File.Delete(strFileName);
            }
        }
        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="strFileName"></param>
        public static void CreatFile(string strFileName)
        {
            System.IO.FileStream myFileStream = new System.IO.FileStream(strFileName, System.IO.FileMode.Create);
            myFileStream.Close();
        }
        /// <summary>
        /// 创建目录，如果目录不存在就创建，存在则直接返回。
        /// </summary>
        /// <param name="path"></param>
        public static string CreatePath(string strPath)
        {
            if (!System.IO.Directory.Exists(strPath))
                System.IO.Directory.CreateDirectory(strPath);
            return strPath;
        }
        /// ******************************************************************
        /// <summary>
        /// 向文件添加文本
        /// </summary>
        /// <param name="strFileName">文件路径</param>
        /// <param name="strText">文件内容</param>
        /// <param name="strEncode">存储编码</param>
        /// <returns></returns>
        public static bool SaveFile(string strFileName, string strText, string strEncode)
        {
            if (strText.Length < 1) { return false; }

            StreamWriter urlWrite = new StreamWriter(strFileName, false, Encoding.GetEncoding(strEncode));
            urlWrite.Write(strText);
            urlWrite.Close();

            return true;
        }

        ///******************************************************************

        public static bool FileExist(string strPath)
        {
            return File.Exists(strPath);
        }
        ///******************************************************************
        /// <summary>
        ///   //检查并创建文件
        /// </summary>
        /// <param name="strFileName">文件全路径</param>
        /// <param name="boolDelExist">如果文件存在是否删除</param>
        /// <returns></returns>
        ///******************************************************************     
        public static string CheckAndCreateFile(string strFileName, bool boolDelExist)
        {
            strFileName = strFileName.Replace("/", "\\");
            //存在文件
            if (File.Exists(strFileName))
            {
                if (boolDelExist)
                {
                    File.Delete(strFileName);
                    CreatFile(strFileName);
                }
            }
            else //不存在文件
            {
                int end = strFileName.LastIndexOf("\\");
                if (end > 0)
                {
                    string strFolder = strFileName.Substring(0, end);
                    if (!Directory.Exists(strFolder))
                    {
                        Directory.CreateDirectory(strFolder);
                    }
                }
                CreatFile(strFileName);
            }
            return strFileName;
        }

        public static void CreatDefaultXml(string strFileName)
        {
            string strMyXml = "<?xml version=\"1.0\" encoding=\"gb2312\"?><configuration></configuration>";
            System.IO.FileStream myFileStream = new System.IO.FileStream(strFileName, System.IO.FileMode.Create);
            myFileStream.Close();
            StreamWriter urlWrite = new StreamWriter(strFileName, false, Encoding.GetEncoding("gb2312"));
            urlWrite.Write(strMyXml);
            urlWrite.Close();
        }
        //用户WINDOW应用程序与WEN项目CONFIG切换
        public static string GetConfigPath(string path)
        {
            string strPath = path;
            if (!System.IO.File.Exists(path) || strPath.IndexOf(":") == -1)
            {
                //string strPath1 = System.IO.Directory.GetCurrentDirectory();
                //string strPath2 = System.Environment.CurrentDirectory;
                //以上两种取个人文档地址，下面两种取WEB文件夹路径
                //strPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

                strPath = System.AppDomain.CurrentDomain.BaseDirectory + path;
            }
            return strPath;
        }

        /// <summary>
        /// 获得当前绝对路径
        /// </summary>
        /// <param name="strMath">文件名</param>
        /// <returns>绝对路径</returns>
        public static string GetImgPath(string strMath)
        {
            string strPath = "\\Photo\\";
            string strMonth = DateTime.Now.Month.ToString();
            if (strMonth.Length == 1) { strMonth = "0" + strMonth; }
            strPath += DateTime.Now.Year.ToString() + strMonth + "\\";
            string strTime = DateTime.Now.ToString() + DateTime.Now.Millisecond.ToString();
            strPath += strTime.Replace(" ", "").Replace("-", "").Replace(":", "");
            if (strMath == null || strMath.Length < 1)
            {
                strPath += ".jpg";
            }
            else
            {
                strPath += "-" + strMath + ".jpg";
            }
            return strPath;
        }
        /// <summary>
        /// 判断文件名是否为浏览器可以直接显示的图片文件名
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <returns>是否可以直接显示</returns>
        public static bool IsImgFilename(string filename)
        {
            filename = filename.Trim();
            if (filename.EndsWith(".") || filename.IndexOf(".") == -1)
            {
                return false;
            }
            string extname = filename.Substring(filename.LastIndexOf(".") + 1).ToLower();
            return (extname == "jpg" || extname == "jpeg" || extname == "png" || extname == "bmp" || extname == "gif");
        }

        public static string SearchConfigPath()
        {
            string BaseDic = System.AppDomain.CurrentDomain.BaseDirectory;
            int i = 0;
            DirectoryInfo info = new DirectoryInfo(BaseDic);
            while (i < 8)
            {
                //要查的目录必须是小写
                DirectoryInfo[] tempInfo = info.GetDirectories("snipconfig");
                if (tempInfo.Length > 0)
                {
                    BaseDic = tempInfo[0].FullName;
                    break;
                }
                else
                {
                    info = info.Parent;
                    tempInfo = info.GetDirectories("web");
                    if (tempInfo.Length > 0)
                    {
                        info = tempInfo[0];
                    }
                }
                i++;
            }
            return BaseDic.TrimEnd('\\');
        }

        /// <summary>
        /// 索引一个文件夹 name  size time path
        /// </summary>
        /// <param name="strDirectory">文件夹路径</param>
        public static DataTable IndexDic(string strDirectory)
        {
            DirectoryInfo directory = new DirectoryInfo(strDirectory);
            DataTable dtFile = new DataTable();
            dtFile.Columns.Add("name", typeof(string));
            dtFile.Columns.Add("size", typeof(string));
            dtFile.Columns.Add("time", typeof(string));
            dtFile.Columns.Add("path", typeof(string));
            dtFile.Columns.Add("type", typeof(string));
            DataRow newRow;
            foreach (FileInfo fi in directory.GetFiles())
            {
                //跳过临时文件
                if (fi.Name.StartsWith("~"))
                    continue;
                newRow = dtFile.NewRow();
                newRow["name"] = fi.Name;
                newRow["size"] = fi.Length / 100;
                newRow["time"] = fi.LastWriteTime.ToString();
                newRow["path"] = fi.FullName;
                newRow["type"] = fi.Extension.Replace(".", "");
                dtFile.Rows.Add(newRow);
            }
            return dtFile;
        }
        /// <summary>
        /// 获取应用程序所在根目录，并拼接传入的目录名称
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetCurrPath(string name)
        {
            return System.AppDomain.CurrentDomain.BaseDirectory + name;
        }

       
    }
}
